package com.centling.qps;

import java.util.concurrent.CompletableFuture;

/**
 * Created by centling on 2016/5/20.
 */

class POJO {

    private int credit;

    private String name;


    POJO(int credit, String name) {
        this.credit = credit;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getCredit() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return credit;
    }

    public void setCredit(int credit) {
        this.credit = credit;
    }

    public static POJO getPOJO(int credit, String name) {
        return new POJO(credit, name);
    }

}


public class CompleteableFutureTest {

    public static void main(String[] args) throws Exception {

        long start = System.currentTimeMillis();

        CompletableFuture<POJO> pojoCompletableFuture = CompletableFuture.supplyAsync(() -> POJO.getPOJO(1, "POJO1"));

        CompletableFuture<Integer> credit1 = pojoCompletableFuture
            .thenApplyAsync(pojo -> pojo.getCredit() * 2);

        CompletableFuture<Integer> credit2 = pojoCompletableFuture
            .thenApplyAsync(pojo -> pojo.getCredit() * 2).handleAsync((ok,ex)->ok*4);

        CompletableFuture<Integer> [] cfs = new CompletableFuture[]{credit1, credit2};

        CompletableFuture.allOf(cfs).join();


        int result = credit1.thenCombineAsync(credit2, Integer::sum).get();
        long end = System.currentTimeMillis();

        System.out.println("completable future result = " + result + " in " + (end - start) + " million seconds");
        Thread.sleep(4000);
        System.out.println("after 5 seconds sleep...");

    }


}
